﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebSite.Core;
using Common;

namespace WebSite
{
    public partial class SubmitInfo : BasePage
    {
        public Maticsoft.Model.CarrefourCover.Baby currentBabyInfo = null;
        public string currentBabyLiveImage1 = "";
        public string currentBabyLiveImage2 = "";

        protected void Page_Load( object sender, EventArgs e )
        {
            Response.Cache.SetNoServerCaching();
            Response.Cache.SetNoStore();

            if (Project_Session.CurrentUserBaby == null)
            {
                base.AlertMessageBack("决赛即将开始，敬请期待");
            }
            else
            {
                base.AlertMessage("决赛即将开始，敬请期待", "/BabyGroup.aspx");
            }
            return;     

            Core.NavHelper.SetNavMenuSelectedIndex( 1 );
            Core.NavHelper.SetNavStepCurrentStep( 2 );
            if (!IsPostBack)
            {
                currentBabyInfo = Project_Session.RefreshBabyInfo();

                if (currentBabyInfo != null)
                {
                    if (NullableHelper.CastValueType( currentBabyInfo.ConfirmTeamId ) != 0)
                    {
                        AlertMessageBack( "您已经组队，无法进行资料修改" );
                    }

                    tbBabyName.Value = currentBabyInfo.BabyName;
                    var birthday = currentBabyInfo.BabyBirthday.HasValue ? currentBabyInfo.BabyBirthday.Value : DateTime.Now;
                    SetSelectedIndexByText( selectBirthdayYear, birthday.Year.ToString() );
                    SetSelectedIndexByText( selectBirthdayMonth, birthday.Month.ToString() );
                    SetSelectedIndexByText( selectBirthdayDay, birthday.Day.ToString() );

                    tbHeight.Value = currentBabyInfo.Height.ToString();
                    tbWeight.Value = currentBabyInfo.Weight.ToString();
                    tbIntro.Value = currentBabyInfo.Introduction;

                    rbSexMale.Checked = currentBabyInfo.BabySex.Value == 1;
                    rbSexFemale.Checked = !rbSexMale.Checked;

                    SetSelectedIndexByText( selectMilkBrand, currentBabyInfo.MilkBrand );
                    tbParentFirstName.Value = currentBabyInfo.ParentFirstName;
                    tbParentLastName.Value = currentBabyInfo.ParentLastName;
                    // tbParentType.Value = currentBabyInfo.ParentType;
                    tbAddress.Value = currentBabyInfo.LiveRoad;
                    tbPostCode.Value = currentBabyInfo.ZipCode;
                    tbEmail.Value = currentBabyInfo.EMail;

                    SetSelectedIndexByValue( selectParentType, currentBabyInfo.ParentType.ToString() );

                    tbTeamName.Value = currentBabyInfo.BabyTeamName;
                    tbTeamDeclaration.Value = currentBabyInfo.BabyTeamDeclaration;

                    // 读取生活照
                    Maticsoft.BLL.CarrefourCover.Image bllimage = new Maticsoft.BLL.CarrefourCover.Image();
                    var liveimageModel = bllimage.GetModelList( "ImgTargetId = " + currentBabyInfo.Id.ToString() );

                    liveimageModel = liveimageModel.OrderBy( p => p.ImgType ).ToList();
                    if (liveimageModel.Count > 0)
                    {
                        currentBabyLiveImage1 = liveimageModel[0].ImgUrl;
                    }
                    if (liveimageModel.Count > 1)
                    {
                        currentBabyLiveImage2 = liveimageModel[1].ImgUrl;
                    }
                }
            }
            else
            {

                currentBabyInfo = Project_Session.CurrentUserBaby;
            }
        }

        protected void ibSave_Click( object sender, ImageClickEventArgs e )
        {
            if (tbvcode.Value.ToLower() != Session["VCODE"].ToString().ToLower())
            {
                AlertMessageBack( "验证码不正确" );
            }

            DateTime birthday = new DateTime(
                Convert.ToInt32( selectBirthdayYear.Value ),
                Convert.ToInt32( selectBirthdayMonth.Value ),
                Convert.ToInt32( selectBirthdayDay.Value )
                );

            if (birthday >= new DateTime( 2012, 4, 1 ) || birthday < new DateTime( 2009, 10,1 ))
            {
                AlertMessageBack( "只有2009年10月～2012年4月出生的宝宝才能参与活动" );
            }

            int weight = 0, height = 0;
            if (!int.TryParse( tbWeight.Value, out weight ))
            {
                weight=0;
            }
            if (!int.TryParse( tbHeight.Value, out height ))
            {
                height=0;
            }

            bool isadd = false;
            if (currentBabyInfo == null)
            {
                currentBabyInfo = new Maticsoft.Model.CarrefourCover.Baby();
                currentBabyInfo.Id = Project_Session.CurrentUser.UserId;

                isadd = true;
            }

            currentBabyInfo.BabyName = tbBabyName.Value;
            currentBabyInfo.BabyHeadImg = Request.Form["hdHeadImage"]; // "/images/samplephoto2_300.JPG";
            currentBabyInfo.BabyBirthday = birthday;
            currentBabyInfo.BabySex = rbSexMale.Checked ? 1 : 2;
            currentBabyInfo.Height = height;
            currentBabyInfo.Weight = weight;
            currentBabyInfo.Introduction = tbIntro.Value;
            currentBabyInfo.MilkBrand = selectMilkBrand.Value;
            currentBabyInfo.ParentFirstName = tbParentFirstName.Value;
            currentBabyInfo.ParentLastName = ""; // tbParentLastName.Value;
            currentBabyInfo.ParentType = Convert.ToInt32( selectParentType.Value );
            currentBabyInfo.LiveProvince = Request["selectProvince"];
            currentBabyInfo.LiveCity = Request["selectCity"];
            currentBabyInfo.LiveArea = Request["selectArea"];
            currentBabyInfo.LiveRoad = tbAddress.Value;
            currentBabyInfo.ZipCode = tbPostCode.Value;
            currentBabyInfo.EMail = tbEmail.Value;
            currentBabyInfo.Status = 1;
            currentBabyInfo.CreateTime = DateTime.Now;
            currentBabyInfo.Ip = Request.UserHostAddress;

            currentBabyInfo.BabyTeamName = tbTeamName.Value;
            currentBabyInfo.BabyTeamDeclaration = tbTeamDeclaration.Value;

            Maticsoft.BLL.CarrefourCover.Baby bll = new Maticsoft.BLL.CarrefourCover.Baby();
            if (isadd)
            {
                bll.Add( currentBabyInfo );
            }
            else
            {
                bll.Update( currentBabyInfo );
            }

            // 同步更新team的冗余信息
            int teamID = NullableHelper.CastValueType( currentBabyInfo.ConfirmTeamId );
            if ( teamID != 0)
            {
                Maticsoft.BLL.CarrefourCover.Team teambll = new Maticsoft.BLL.CarrefourCover.Team();
                var teammodel = teambll.GetModel( teamID );
                if (teammodel != null)
                {
                    // 如果是A宝宝，同步更新队伍名
                    if (teammodel.BabyAId == currentBabyInfo.Id)
                    {
                        teammodel.TeamName = currentBabyInfo.BabyTeamName;
                        teammodel.BabyAName = currentBabyInfo.BabyName;
                    }
                    else
                    {
                        teammodel.BabyBName = currentBabyInfo.BabyName;
                    }
                    teambll.Update( teammodel );
                }
            }

            // 保存生活照图片
            Maticsoft.BLL.CarrefourCover.Image bllimage = new Maticsoft.BLL.CarrefourCover.Image();
            var liveimageModel = bllimage.GetModelList( "ImgTargetId = " + currentBabyInfo.Id.ToString() );
            if (liveimageModel.Count > 0)
            {
                bllimage.DeleteList( string.Join( ",", liveimageModel.Select( p => p.Id ).ToArray() ) );
            }

            int cnt = 1;

            List<Maticsoft.Model.CarrefourCover.Image> listLiveImage = new List<Maticsoft.Model.CarrefourCover.Image>();
            if (!string.IsNullOrEmpty( Request.Form["hdLiveImage1"] ))
            {
                listLiveImage.Add( new Maticsoft.Model.CarrefourCover.Image()
                {
                    ImgTargetId = currentBabyInfo.Id,
                    Ip = Request.UserHostAddress,
                    ImgUrl = Request.Form["hdLiveImage1"],
                    ImgType = cnt,
                    Status = 1,
                    CreateTime = DateTime.Now
                } );

                cnt++;
            }
            if (!string.IsNullOrEmpty( Request.Form["hdLiveImage2"] ))
            {
                listLiveImage.Add( new Maticsoft.Model.CarrefourCover.Image()
                {
                    ImgTargetId = currentBabyInfo.Id,
                    Ip = Request.UserHostAddress,
                    ImgUrl = Request.Form["hdLiveImage2"],
                    ImgType = cnt,
                    Status = 1,
                    CreateTime = DateTime.Now
                } );

                cnt++;
            }
            foreach (var m in listLiveImage)
            {
                bllimage.Add( m );
            }

            Project_Session.RefreshBabyInfo();
            base.AlertMessage( "宝宝信息保存成功", "/LookingForTeam.aspx" );
        }
    }
}